/**
 * 
 */
package sk.stuba.fiit.foo07.genex.gui;

import java.sql.Connection;
import java.util.ArrayList;

import javax.swing.event.TreeExpansionEvent;
import javax.swing.event.TreeWillExpandListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.ExpandVetoException;
import javax.swing.tree.TreePath;

import sk.stuba.fiit.foo07.genex.beans.Category;
import sk.stuba.fiit.foo07.genex.beans.Test;
import sk.stuba.fiit.foo07.genex.dao.CategoryDao;
import sk.stuba.fiit.foo07.genex.dao.CategoryDaoDerby;
import sk.stuba.fiit.foo07.genex.dao.TestDao;
import sk.stuba.fiit.foo07.genex.dao.TestDaoDerby;

/**
 * @author _mizu_
 * 
 */
public class TestCategoryTreeListener implements TreeWillExpandListener {
    CategoryDao catDao;
    TestDao testDao;

    public TestCategoryTreeListener(Connection c) {
        catDao = new CategoryDaoDerby(c);
        testDao = new TestDaoDerby(c);
    }

    @Override
    public void treeWillCollapse(TreeExpansionEvent event)
            throws ExpandVetoException {
        TreePath path = event.getPath();
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) path
                .getLastPathComponent();
        node.removeAllChildren();
        node.add(new DefaultMutableTreeNode("camuflage"));
    }

    @Override
    public void treeWillExpand(TreeExpansionEvent event)
            throws ExpandVetoException {
        TreePath path = event.getPath();
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) path
                .getLastPathComponent();
        node.removeAllChildren();

        Object o = node.getUserObject();
        if (!(o instanceof Category))
            return;
        Category c = (Category) o;

        //TODO 
        //pridane odchytavanie vynimiek
        try {
            // pridanie podkategorii
            ArrayList<Category> subCats = catDao.getTestCategoriesByParentID(c
                    .getCategoryID());
            for (Category cat : subCats) {
                DefaultMutableTreeNode toAdd = new DefaultMutableTreeNode(cat);
                node.add(toAdd);

                ArrayList<Test> innerTests = testDao.getTestsByCategoryID(cat
                        .getCategoryID());

                if (catDao.hasTestSubcategories(cat.getCategoryID())
                        || innerTests.size() > 0)
                    toAdd.add(new DefaultMutableTreeNode("camuflage"));
            }

            // pridanie testov
            ArrayList<Test> tests = testDao.getTestsByCategoryID(c
                    .getCategoryID());
            for (Test test : tests)
                node.add(new DefaultMutableTreeNode(test));

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
